//
//  PhototPickDemoController.swift
//  SwiftDemo2
//
//  Created by ShareAnimation on 2017/9/12.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MobileCoreServices
import TZImagePickerController

class PhototPickDemoController: UIViewController,TZImagePickerControllerDelegate {
    
    
    
    fileprivate var  _pickerCollectionView: UICollectionView!
    fileprivate var pickerCollectionView: UICollectionView {
        get {
            if _pickerCollectionView != nil {
                return _pickerCollectionView
            }
            let layout = UICollectionViewFlowLayout()
            
            _pickerCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
            _pickerCollectionView.backgroundColor = UIColor.white
            _pickerCollectionView.delegate = self
            _pickerCollectionView.dataSource = self
            
            _pickerCollectionView.register(PhotoPickViewCell.self, forCellWithReuseIdentifier: "cell")
            
            return _pickerCollectionView
        }
    }

    fileprivate var currentPhotos = [UIImage]() {
        willSet {
            if let handler = self.photoPickHandler {
                handler(newValue)
            }
        }
    }
    
    var photoPickHandler: (([UIImage]) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        self.setupViews()
    }
    
    func setupViews() {
        self.view.addSubview(self.pickerCollectionView)
        self.pickerCollectionView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
    }
    
    func showPhotoPickerSheet() {
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let takePhotoAction = UIAlertAction(title: "拍照", style: .default) { (action) in
            let imagePickerController = UIImagePickerController()
            imagePickerController.delegate = self
            imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
            imagePickerController.allowsEditing = true
            imagePickerController.showsCameraControls = true
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear
            imagePickerController.mediaTypes = [kUTTypeImage as String]
            
            self.present(imagePickerController, animated: true, completion: nil)
        }
        
        let choicePhotoAction = UIAlertAction(title: "从相册选择", style: .default) { (action) in
            let imagePicker = TZImagePickerController.init(maxImagesCount: 4 - self.currentPhotos.count, delegate: self)
            imagePicker?.didFinishPickingPhotosHandle = {[unowned self](photos, assets,isSelectOriginalPhoto) in
                if photos != nil {
                    self.currentPhotos += photos!
                    self.pickerCollectionView.reloadData()
                }
                
            }
            self.present(imagePicker!, animated: true, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertController.addAction(takePhotoAction)
        alertController.addAction(choicePhotoAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
        
    }
}

extension PhototPickDemoController: UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.currentPhotos.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PhotoPickViewCell
        cell.deleteImageActionHandler = {//删除按钮点击
            self.currentPhotos.remove(at: indexPath.row)
            collectionView.reloadData()
        }
        
        if indexPath.row == self.currentPhotos.count {//最后一个item显示『添加』
           cell.profilePhotoImageView.image = UIImage(named: "plus")
            cell.closeButton.isHidden = true
            cell.profilePhotoImageView.isUserInteractionEnabled = false
        }
        else {
            cell.profilePhotoImageView.image = self.currentPhotos[indexPath.row]
            cell.closeButton.isHidden = false
            cell.profilePhotoImageView.isUserInteractionEnabled = true
        }
        
        return cell
    }
    
    //MARK:UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //每个item的大小
        return CGSize(width: (UIScreen.main.bounds.width-64)/4, height: (UIScreen.main.bounds.width-64)/4)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        //定义每个item的Margin
        return UIEdgeInsetsMake(20, 8, 20, 8)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == self.currentPhotos.count {//最后一个item显示『添加照片』
            self.showPhotoPickerSheet()
        }
        
    }
    
    
    
}

extension PhototPickDemoController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    //MARK:(UIImagePickerControllerDelegate & UINavigationControllerDelegate)
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let photo = info[UIImagePickerControllerOriginalImage]
        
        self.dismiss(animated: true) {
            if photo != nil {
                self.currentPhotos.append(photo! as! UIImage)
                self.pickerCollectionView.reloadData()
            }
        }
    }
}
